#include"Contact.h"
#include <stdio.h>
void InitContact(Contact *con)
{
    con->data=(PeopleInfo*)malloc(sizeof(PeopleInfo)*3);
    con->sz=0;
    con->capacity=Defalut_Size; 
    //加载数据到Contact
    DumpContact(con);
}
void DumpContact(Contact *con)
{
    FILE*fcon=fopen("contact.txt","r");
    PeopleInfo tmp={0}; 
    while(fread(&tmp,sizeof(PeopleInfo),1, fcon))
    {
        con->data[con->sz]=tmp;
        con->sz++;
        if(con->sz==con->capacity)
        {
            AddMem(con);
        }
    } 
    fclose(fcon);
    fcon=NULL;
}
void AddMem(Contact *con)
{
    PeopleInfo* tmp=(PeopleInfo*)realloc(con->data,(con->capacity+2)*sizeof(PeopleInfo));
    if(tmp==NULL)printf("AddMem创建失败");
    con->data=tmp;
    con->capacity+=Inc_sz; 

}
void AddContact(Contact *con)
{
    if(con->sz==con->capacity)
        {
            AddMem(con);
        }
    printf("请输入姓名");
    scanf("%s",con->data[con->sz].name);
    printf("请输入性别");
    scanf("%s",con->data[con->sz].sex);
    printf("请输入住址");
    scanf("%s",con->data[con->sz].addr);
    printf("请输入电话号码");
    scanf("%s",con->data[con->sz].tele);
    printf("请输入年龄");
    scanf("%d",&(con->data[con->sz].age));
    con->sz++;
}
void ShowContact(const Contact *con)
{   printf("%-20s\t%-20s\t%-20s\t%-20s\t%-4s\n","姓名","性别","住址","电话","年龄");
    for(int i=0;i<con->sz;++i)
    {
        printf("%-20s\t%-20s\t%-20s\t%-20s\t%-4d\n",con->data[i].name
        ,con->data[i].sex,con->data[i].addr,con->data[i].tele,con->data[i].age);
    }
}
int FindContact(const Contact *con)
{
    char name[20];
    int flag=-1;
    printf("请输入要查找的名字");
    scanf("%s",name);
    for(int i=0;i<con->sz;i++)
    {
        if(strcmp(con->data[i].name, name)==0)
        {
            flag=i;
            break;
        }
    }
    if(flag==-1)
    {
        printf("未找到");
        return -1;
    }
    return flag;
}
    

void DelContact(Contact *con)
{
 if(con->sz==0)
    {
        printf("通讯录为空，无法删除");
        return;
    }
    int flag=FindContact(con);
    if(flag!=-1)
    {
        memmove(con->data+flag, con->data+flag+1,(con->sz-1-flag)*sizeof(PeopleInfo));
        con->sz--;
        printf("删除成功");
    }
}
void ModifyContact(Contact *con)
{
    int flag=FindContact(con);
    printf("请输入姓名");
    scanf("%s",con->data[flag].name);
    printf("请输入性别");
    scanf("%s",con->data[flag].sex);
    printf("请输入住址");
    scanf("%s",con->data[flag].addr);
    printf("请输入电话号码");
    scanf("%s",con->data[flag].tele);
    printf("请输入年龄");
    scanf("%d",&(con->data[flag].age));
}
void Destroy(Contact *con)
{
    free(con->data);
    con->data=NULL;
    con->capacity=0;
    con->sz=0;
    con=NULL;
}
void SaveContact(Contact *con)
{
    FILE *fcon=fopen("contact.txt","w");
    if(fcon==NULL)
    {
        perror("文件打开失败");
        return;
    }
    for(int i=0;i<con->sz;i++)
    {
        fwrite(con->data+i,sizeof(PeopleInfo),1,fcon);

    }
    fclose(fcon);
    fcon=NULL;
    printf("保存数据成功");
}